<template>
  <div class="flow-editor">
    
    <!-- 标签栏 -->
    <div class="tab-bar" ref="tabBarRef">
      <div v-for="project in validProjects" :key="project.id" class="tab" :style="{width:tabW+'px'}"
        :class="{ active: project.id === currentProjectId }" @click="setCurrentProject(project.id)" >
        <div v-if="project.loaded" style="overflow:hidden;white-space:nowrap;">{{project.name}}</div>

        <button @click.stop="closeProject(project.id)" class="close-btn">X</button>
      </div>
      <button @click="handleAddTab" id="Addbtn" class="add-btn" :style="{width:addtabW+'px'}">+</button>
    </div>
    <hr />

    <div class="editor">
      <Project v-if="currentProjectId&&checkopened(currentProjectId)" />
    </div>
  </div>
  <a-modal v-model:open="addProjectModal" title="select a template to begin" style="top: 100px" :width="600" >
    <div class="template-container">
      <div class="t-left">
        <div v-for="(item,index) in template_op" :key="item.id">
          <a-button @click="templateIndex=index" type="default" style="margin-top:5px; width:90%;">
            {{ item.label }}
          </a-button>
        </div>
      </div>
      <hr class="vertical-line">
      <div class="t-right">
        <div v-if="templateIndex>=0" class="template-description" >
          <div style="font-size:20px;font-family:serif">{{ template_op[templateIndex].label }}</div>
          {{ template_op[templateIndex].description }}
        </div>
      </div>
    </div>
    <template #footer>
      <a-button @click="addNewProject(template_op[templateIndex])" :disabled="templateIndex<0" type="default">
       create
      </a-button>
    </template>
  </a-modal>
</template>
  
  <script lang="ts" setup>
  import { useProjectsStore } from '../stores/projectsStore';
  import { defineComponent, ref, computed, onMounted, nextTick, watch } from 'vue';

  import Project from '../components/Project.vue'; // 替换为正确的路径
  import { template_op } from '../components/ts/templateProject';

  const projectsStore = useProjectsStore();
  const currentProjectId = computed(() => { return projectsStore.currentProjectId });

  onMounted(() => {
    projectsStore.initializeProjects();
  })
  //安全加载
  const validProjects = computed(() => {
    return projectsStore.projects.filter(project => project &&project?.is_opened===true&&project.id && project.loaded && project.content&&Object.keys(project.content).length > 0);
  });
  // 设置当前选中的Project
  const setCurrentProject = (id: string) => {
    projectsStore.setCurrentProject(id);
  };
//检查某个项目是否处于打开状态
const checkopened=(id:string)=>{
  return projectsStore.projects.find(project => project.id === id)?.is_opened===true
}
  // 删除项目
  const closeProject = (projectId: string) => {
    // if (currentProjectId.value !== projectId) {
    //   return;//暂时
    // }
    projectsStore.removeProject(projectId);  // 从store移除项目
  };
  const addProjectModal = ref(false)
  const templateIndex = ref(-1)
  // 添加新的Project
  const addNewProject = (template: any) => {
    projectsStore.addProject(template.value,template.description, template.content)
    //projectsStore.addProject("New Project", {initialEdges:[], initialNodes:[{"id": "A1", "type": "agent", "position": {"x": 300, "y": 300}, "data": {"name": "Agent 1"}, "style": {}}, {"id": "http", "type": "http", "position": {"x": 0, "y": 0}, "data": {"name": "Http/WS Entry"}, "style": {"backgroundColor": "rgba(116, 245, 80, 0.5)", "height": "200px", "width": "400px"}}, {"id": "A-IF-1", "type": "agent-if", "position": {"x": 300, "y": 0}, "data": {"name": "IF Agent"}, "style": {}}, {"id": "A-Tool-Execute-1", "type": "tool-execute", "position": {"x": 0, "y": 300}, "data": {"name": "Tool Execute"}, "style": {"backgroundColor": "rgba(80, 121, 245, 0.5)", "height": "200px", "width": "400px"}}, {"id": "Tool-1", "type": "tool", "position": {"x": 300, "y": 600}, "data": {"name": "Tool 1"}, "style": {}}]});
    addProjectModal.value = false
  };
  //顶部标签栏相关
  const addtabW = ref(30)
  const maxTabCount = computed(() => {
    if (!tabBarRef.value) {
      return 0
    }
    return Math.floor((tabBarRef.value?.offsetWidth - 20 - addtabW.value) / minTabW.value)
  })
  let tabBarRef = ref<HTMLDivElement | null>(null)
  const initTabW = ref(200)
  const minTabW = ref(70)
  //标签栏宽度变化时，动态调整标签宽度
  let i = 1
  watch(() => tabBarRef.value?.getBoundingClientRect().width, () => {
    minTabW.value += (i++ % 2 == 0 ? 1 : -1)
  })
  const tabW = computed(() => {
    let tabcount = validProjects.value.length

    let tablength = initTabW.value * tabcount + addtabW.value + 10

    if (tabcount === 0 || !tabBarRef.value || tabBarRef.value.getBoundingClientRect().width > tablength) {
      return initTabW.value
    }

    const realWidth = tabBarRef.value.getBoundingClientRect().width
    return (realWidth - 10 - addtabW.value) / tabcount
  })

  const handleAddTab = () => {
    if (validProjects.value.length >=maxTabCount.value){
      return
    }
    addProjectModal.value=true
  }
    </script>
  <style scoped lang="scss">
  .flow-editor {
    width: 100%;
    height: 100%;
    display: flex;
    min-height:600px;
    flex-direction: column;
    position:relative;
  }

  .tab-bar {
    height: 2rem;
    min-height:35px;
    width:100%;
    display: flex;
    flex-wrap: nowrap;
        background: radial-gradient(
        circle at center, 
        rgba(173, 216, 230, 0)10%,  
        rgba(142, 201, 220, 0.3) 60%,
        rgba(75, 191, 230, 0.684) 100%
    );
    position: relative;
    overflow-x: hidden;
  }

  .tab {
    background: #f0f0f0;
    overflow: hidden;
    margin-right: 0px;
    height: 100%;
    padding: 10px;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
     transition: width 0.3s ease;
    &:hover{
      opacity: 0.8;
    }
  }

  .tab.active {
    background: #d0d0d0;
  }

  .close-btn {
    border: none;
    margin-left: 10px;
    border-radius: 50%;
    &:hover{
      opacity:1;
      color:#1b1a19;
      background: #d0d0d0;
    }
  }

  .add-btn {
    border: none;
    margin-left: 0px;
    background: #f0f0f0;
    border-radius: 100%;
    text-align: center;
    font-size: 1rem;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover{
      background-color: #d0d0d0;
    }
  }

  .editor {
    width: 100%;
    height:calc(100% - 35px);
    position:relative;
    padding:0;
    margin:0;
  }

  textarea {
    width: 100%;
    height: 300px;
    padding: 10px;
    font-size: 16px;
    border-radius: 5px;
    border: 1px solid #ddd;
  }

  .template-container {
    display: flex;
    position: relative;
    height: 300px;

    .t-left {
      flex: 3;
      height: 100%;
      align-items: center;
      position: relative;
      overflow-y: auto;
    }

    .t-left::-webkit-scrollbar {
      width: 8px;
      /* 滚动条宽度 */
    }

    .t-left::-webkit-scrollbar-track {
      background: #f1f1f1;
      /* 滚动条轨道颜色 */
      border-radius: 8px;
    }

    .t-left::-webkit-scrollbar-thumb {
      background: #87ecdd;
      /* 滚动条滑块颜色 */
      border-radius: 8px;
    }

    .t-left::-webkit-scrollbar-thumb:hover {
      background: #4ee3c3;
      /* hover 时高亮 */
    }

    .t-right {
      flex: 7;
      height: 100%;
      overflow-y: auto;
       background-color: #c0bcbc49;

      .template-description {
        white-space: pre-wrap;
        font-size: 14px;
        font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
        padding: 10px;
      }
    }
  }

  .vertical-line {
    width: 1px;
    height: 100%;
    /* 控制高度 */
    border: none;
    background-color: #000;
    /* 颜色 */
  }

</style>
  
